package cn.stylefeng.guns.modular.time.controller;

import cn.stylefeng.roses.kernel.scanner.api.annotation.ApiResource;
import cn.stylefeng.roses.kernel.scanner.api.annotation.GetResource;
import cn.stylefeng.roses.kernel.scanner.api.annotation.PostResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Coze 工作流控制器：提供查询、添加、修改、删除、运行工作流的接口。
 * - 采用内存存储以快速集成，后续可替换为数据库持久化。
 */
@RestController
@ApiResource(name = "Coze工作流")
public class CozeWorkflowController {

    /** 内存存储与ID生成器 */
    private final Map<Long, Workflow> store = new ConcurrentHashMap<>();
    private final AtomicLong idGen = new AtomicLong(1000);

    /**
     * 查询全部工作流。
     */
    @GetResource(name = "查询全部工作流", path = "/time/coze/workflows", requiredLogin = false, requiredPermission = false)
    public List<Workflow> list() {
        return new ArrayList<>(store.values());
    }

    /**
     * 查询单个工作流。
     */
    @GetResource(name = "查询工作流详情", path = "/time/coze/workflows/{id}", requiredLogin = false, requiredPermission = false)
    public ResponseEntity<Workflow> get(@PathVariable Long id) {
        Workflow wf = store.get(id);
        if (wf == null) return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        return ResponseEntity.ok(wf);
    }

    /**
     * 新增工作流。
     */
    @PostResource(name = "新增工作流", path = "/time/coze/workflows", requiredLogin = false, requiredPermission = false)
    public Workflow create(@RequestBody WorkflowCreateRequest req) {
        long id = idGen.incrementAndGet();
        Workflow wf = new Workflow();
        wf.setId(id);
        wf.setName(req.getName());
        wf.setDescription(req.getDescription());
        wf.setContent(req.getContent());
        wf.setStatus("idle");
        wf.setCreatedAt(Instant.now().toString());
        wf.setUpdatedAt(wf.getCreatedAt());
        store.put(id, wf);
        return wf;
    }

    /**
     * 更新工作流。
     * 避免与删除接口冲突，使用明确的更新路径：/time/coze/workflows/{id}/update
     */
    @PostResource(name = "更新工作流", path = "/time/coze/workflows/{id}/update", requiredLogin = false, requiredPermission = false)
    public ResponseEntity<Workflow> update(@PathVariable Long id, @RequestBody WorkflowUpdateRequest req) {
        Workflow wf = store.get(id);
        if (wf == null) return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        if (req.getName() != null) wf.setName(req.getName());
        if (req.getDescription() != null) wf.setDescription(req.getDescription());
        if (req.getContent() != null) wf.setContent(req.getContent());
        wf.setUpdatedAt(Instant.now().toString());
        return ResponseEntity.ok(wf);
    }

    /**
     * 删除工作流。
     * 避免与更新接口冲突，使用明确的删除路径：/time/coze/workflows/{id}/delete
     */
    @PostResource(name = "删除工作流", path = "/time/coze/workflows/{id}/delete", requiredLogin = false, requiredPermission = false)
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        Workflow removed = store.remove(id);
        if (removed == null) return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        return ResponseEntity.noContent().build();
    }

    /**
     * 运行工作流：模拟执行并返回结果。
     */
    @PostResource(name = "运行工作流", path = "/time/coze/workflows/{id}/run", requiredLogin = false, requiredPermission = false)
    public ResponseEntity<RunResult> run(@PathVariable Long id) {
        Workflow wf = store.get(id);
        if (wf == null) return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        wf.setStatus("running");

        // 模拟执行过程
        RunResult result = new RunResult();
        result.setWorkflowId(id);
        result.setStartedAt(Instant.now().toString());
        result.setOutput("运行完成: " + Optional.ofNullable(wf.getName()).orElse("未命名工作流"));
        result.setSuccess(true);

        // 更新状态
        wf.setStatus("idle");
        wf.setUpdatedAt(Instant.now().toString());

        return ResponseEntity.ok(result);
    }

    // ==== DTOs ====

    /**
     * 工作流对象。
     */
    public static class Workflow {
        private Long id;
        private String name;
        private String description;
        private String content;
        private String status;
        private String createdAt;
        private String updatedAt;

        public Long getId() { return id; }
        public void setId(Long id) { this.id = id; }
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }
        public String getCreatedAt() { return createdAt; }
        public void setCreatedAt(String createdAt) { this.createdAt = createdAt; }
        public String getUpdatedAt() { return updatedAt; }
        public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; }
    }

    /**
     * 创建请求对象。
     */
    public static class WorkflowCreateRequest {
        private String name;
        private String description;
        private String content;

        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
    }

    /**
     * 更新请求对象。
     */
    public static class WorkflowUpdateRequest {
        private String name;
        private String description;
        private String content;

        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
    }

    /**
     * 运行结果对象。
     */
    public static class RunResult {
        private Long workflowId;
        private String startedAt;
        private boolean success;
        private String output;

        public Long getWorkflowId() { return workflowId; }
        public void setWorkflowId(Long workflowId) { this.workflowId = workflowId; }
        public String getStartedAt() { return startedAt; }
        public void setStartedAt(String startedAt) { this.startedAt = startedAt; }
        public boolean isSuccess() { return success; }
        public void setSuccess(boolean success) { this.success = success; }
        public String getOutput() { return output; }
        public void setOutput(String output) { this.output = output; }
    }
}